var app = getApp()
import ajaxhelper from '../../utils/ajaxhelper.js';
import { signByMd5 } from "../../utils/util";
var Quantity = require('../common/quantity/index.js');
Page(Object.assign({}, Quantity,{
  data: { 
    btnTxt: "获取验证码",
    btnUse: false,
    isBind:true,//是否绑定过手机号
    quantity: {
      quantity: 1,
      min: 1,
      max: 99999
    },
    count:1,//购买数量
    redPackNum:'',//使用红包金额
    totalRedPackNum:0,//个人的红包余额
    totalPrice:0,//总共的价格
  },
  onLoad: function (options) {
    var that=this;
    console.log(options);
    var buyType = options.payType||'BUY';//判断是购买还是赠送；
    var courseItem = options.courseItem||"{}";
    courseItem = JSON.parse(courseItem);
    var chapterCount = courseItem.chapterCount;
    var isBind = wx.getStorageSync('Token_date') && wx.getStorageSync('Token_date').isBind;
    that.setData({
      courseItem,
      chapterCount,
      isBind,
      buyType,
      totalPrice: courseItem.currentPrice
    })
    console.log(courseItem)
    that.getRedPack();//获取红包余额
  },
  handleZanQuantityChange(e) {
    var componentId = e.componentId;
    var quantity = e.quantity;
    this.setData({
      [`${componentId}.quantity`]: quantity,
      count: quantity
    });
    this.setTotalPrice();
  },
  // 设置手机号
  setPhone: function (e) {
    var userPhone = e.detail.value;
    this.setData({
      "userPhone": userPhone
    })
  },
  getVercode: function () {
    var _this = this;
    var userPhone = this.data.userPhone;
    if (!userPhone) {
      wx.showToast({
        title: "请输入手机号码",
        icon: 'loading',
        duration: 2000
      })
    } else if (!(/^1[34578]\d{9}$/.test(userPhone))) {
      wx.showToast({
        title: "手机号码有误",
        icon: 'loading',
        duration: 2000
      })
    }
    else {
      _this.startCount();
      var param = {
        "mobile": userPhone,
      }
      ajaxhelper.post(app.globalData.frontJSHost + "genVCode", param, _this, function (res) {
       console.log(res);
       if (res.result){
         var ticket = res.data && res.data.ticket;
         wx.setStorage({
           key: 'ticket',
           data: ticket,
         })
       }
      },function(res){
        console.log(res)
      });
    }
  },
  startCount: function () {
    var _this = this;
    var num = 60;
    var timer = setInterval(function () {
      num--;
      var str = num + "s";
      _this.setData({
        btnTxt: str,
        btnUse: true
      })
      if (num == 0) {
        clearInterval(timer);
        _this.setData({
          btnTxt: "获取验证码",
          btnUse: false
        })
      }
    }, 1000);
  },
  // 表单提交支付
  formSubmit: function (e) {
    console.log(e)
    var that = this;
    let formData = e.detail.value;
    //let name = formData.name;
    let name = that.data.courseItem.name;
    let sourceImg = that.data.courseItem.coverMain;
    let userPhone = formData.phone||'';
    let section = formData.section;
    // let totalPrice = formData.price.slice(1);
    let totalPrice = Math.round(that.data.totalPrice * 100 * 100) / 100;//计算后的价格 传分
    let verCode = formData.verCode;
    let sourceId = that.data.courseItem.id;//课程id
    var mediaType = that.data.courseItem.mediaType;//类型媒体类型（音频或视频）
    var ticket = wx.getStorageSync('ticket');
    var buyCount = +that.data.count;//购买数量
    var hongbao = Math.round((that.data.redPackNum * 100 || 0)* 100) / 100;//使用的红包金额 传分
    var buyType=that.data.buyType;//购买类型
    console.log(totalPrice)
    var params={
      mediaType : mediaType,
      price: totalPrice,
      sourceId: sourceId,
      sourceName: name,
      sourceType:'ONLINE_COURSE',
      sourceImg: sourceImg,
      // telephone: userPhone,
      // smsCode: verCode,
      buyCount,
      hongbao,
      buyType,
      
    }
    if (!that.data.isBind){ //如果用户没有绑定过手机
      params.telephone = userPhone;
      params.smsCode = verCode;
      params.ticket = ticket;
      if (!userPhone) {
        wx.showToast({
          title: "请输入手机号码",
          icon: 'loading',
          duration: 2000
        })
        return
      } else if (!(/^1[34578]\d{9}$/.test(userPhone))) {
        wx.showToast({
          title: "手机号码有误",
          icon: 'loading',
          duration: 2000
        })
        return
      };
      if (!verCode) {
        wx.showToast({
          title: "请输入手机验证码",
          icon: 'loading',
          duration: 2000
        })
        return
      }
    }
   
    var token = (wx.getStorageSync('Token_date') && wx.getStorageSync('Token_date').Token) || '';
    console.log(params)
    console.log(token)
    ajaxhelper.post(app.globalData.frontJSHost + 'priceResourcePay/v1/createOrder?token=' + encodeURIComponent(token), params, this,function (res) {
      console.log(res)
      if (res.result && res.resultStatus==200) {
        //0元不用掉支付
        if ((res.data.data && !res.data.data.params.hasOwnProperty('errorCode')) || res.data.paySuccess){
          //如果没有绑定过 下订单之后就要存储新的绑定值
          if (!that.data.isBind){
            wx.getStorage({
              key: 'Token_date',
              success: function (resultS) {
                console.log(resultS);
                var Token_date = resultS.data;
                Token_date.isBind = res.data.isBind;
                wx.setStorage({
                  key: 'Token_date',
                  data: Token_date,
                })
              },
            })
          }
          var orderId = res.data.order && res.data.order.orderId;//订单id
          if (res.data.paySuccess) {
            that.paySuccessFun(sourceId, name, totalPrice, orderId, mediaType, hongbao);
            return false
          }
          var payData = res.data.data.params;
          let nonceStr = payData.nonceStr;
          let timeStamp = payData.timeStamp;
          let packageValue = payData.package;
          let signPay = payData.signType;
          let paySign = payData.paySign;
          wx.requestPayment({
            timeStamp: timeStamp,
            nonceStr: nonceStr,
            package: packageValue,
            signType: signPay,
            paySign: paySign,
            success: function (res) {
              console.log(res)
              that.paySuccessFun(sourceId, name, totalPrice, orderId, mediaType, hongbao)
              // 支付成功后关闭音乐，由于有试听地址的原因
              // var backgroundAudioManager = app.backgroundAudioManager;
              // if (backgroundAudioManager.src) {
              //   backgroundAudioManager.stop();
              // }
              // 获取全局音频信息
              // var urlObj = wx.getStorageSync('gloalObjUrl');
              // urlObj = urlObj ? JSON.parse(urlObj) : {};
              // if (urlObj.courseId == sourceId){
              //   console.log('购买了当前的' + sourceId);
              //   urlObj.canView=true;
              //   wx.setStorage({
              //     key: 'gloalObjUrl',
              //     data: JSON.stringify(urlObj),
              //   })
              // }
              // /////
              // if (that.data.buyType=='BUY'){
              //   wx.redirectTo({
              //     url: '../successPurchase/successPurchase?name=' + name + '&price=' + totalPrice + '&id=' + orderId + '&mediaType=' + mediaType + '&sourceId=' + sourceId,
              //   })
              // } else if (that.data.buyType == 'GIFT'){
              //   // 如果是赠送进入的，支付成功跳转到赠送页面
              //   var unitPrice = that.data.courseItem.currentPrice;//单价
              //   var count = this.data.count;//购买数量
              //   var chapterCount = this.data.chapterCount;//集数
              //   wx.redirectTo({
              //     url: '../paySuccess/paySuccess?name=' + name + '&price=' + totalPrice + '&mediaType=' + mediaType + '&sourceId=' + sourceId + '&unitPrice=' + unitPrice + '&count=' + count + '&chapterCount=' + chapterCount,
              //   })
              // }
            },
            fail: function (res) {
              console.log(res)
              // wx.redirectTo({
              //   url: '../orderList/orderList',
              // })
              
            }
          })
        } else {
          wx.showToast({
            title: !!res.data.data.params.errorCodeDesc ? res.data.data.params.errorCodeDesc : "订单出错",
            icon: "none"
          })
        }
      }else{
        wx.showToast({
          title: !!res.message.global ? res.message.global : "请求出错",
          icon: "none"
        })
      }
      
    })
    
  },
  paySuccessFun(sourceId, name, totalPrice, orderId, mediaType,hongbao){
    var that=this;
    // 获取全局音频信息
    var urlObj = wx.getStorageSync('gloalObjUrl');
    urlObj = urlObj ? JSON.parse(urlObj) : {};
    if (urlObj.courseId == sourceId) {
      console.log('购买了当前的' + sourceId);
      urlObj.canView = true;
      wx.setStorage({
        key: 'gloalObjUrl',
        data: JSON.stringify(urlObj),
      })
    }
    /////
    if (that.data.buyType == 'BUY') {
      wx.redirectTo({
        url: '../successPurchase/successPurchase?name=' + name + '&price=' + totalPrice / 100 + '&id=' + orderId + '&mediaType=' + mediaType + '&sourceId=' + sourceId + '&hongbao=' + hongbao/100,
      })
    } else if (that.data.buyType == 'GIFT') {
      // 如果是赠送进入的，支付成功跳转到赠送页面
      var unitPrice = that.data.courseItem.currentPrice;//单价
      var count = this.data.count;//购买数量
      var chapterCount = this.data.courseItem.chapterCount;//集数
      var coverMain = that.data.courseItem.coverMain;//单价      
      wx.redirectTo({
        url: '../paySuccess/paySuccess?name=' + name + '&price=' + totalPrice / 100 + '&mediaType=' + mediaType + '&sourceId=' + sourceId + '&unitPrice=' + unitPrice + '&count=' + count + '&chapterCount=' + chapterCount + '&coverMain=' + coverMain + '&id=' + orderId,
      })
    }
  },
  setMoney(e) {
    console.log(e)
    var money = e.detail.value;
    ///
    money = money.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符  
    money = money.replace(/^\./g, ""); //验证第一个字符是数字而不是  
    money = money.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的  
    money = money.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    money = money.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    ////
    this.setData({
      redPackNum: money
    })
    this.setTotalPrice();
  },
  // 失去焦点的时候  0.0解决这个情况
  blurMoeny(e){
    var money = e.detail.value;
    this.setData({
      redPackNum: +money
    })
  },
  // 获取红包余额 单位是分
  getRedPack(){
    var that=this;
    var token = (wx.getStorageSync('Token_date') && wx.getStorageSync('Token_date').Token) || '';
    ajaxhelper.get(app.globalData.frontJSHost + 'hongbao/account?token=' + encodeURIComponent(token), {}, this,function(res){
      console.log(res)
      if (res.result && res.resultStatus == 200) {
        that.setData({
          totalRedPackNum: that.round(res.data.hongbao/100),
        })
      } else {
        wx.showToast({
          title: !!res.message.global ? res.message.global : "请求出错",
          icon: "loading"
        })
      }
      
    })
  },
  // 计算总价格
  setTotalPrice(){
    var that=this;
    var unitPrice = this.data.courseItem.currentPrice;
    var totalPrice = this.data.count * unitPrice;
    var redPackNum = this.data.redPackNum || 0;
    // 红包金额每一份专辑最多使用30元
    if (redPackNum > this.data.count * 30) {
      redPackNum = this.data.count * 30;
      // that.setData({
      //   redPackNum
      // })
      wx.showToast({
        title: '每份专辑最多使用30元红包',
        icon: 'none'
      })
    }
    //
    if (redPackNum > that.data.totalRedPackNum) {
      redPackNum = that.data.totalRedPackNum;
      // that.setData({
      //   redPackNum
      // })
    }
    if (totalPrice < redPackNum){
      redPackNum = totalPrice;
      // that.setData({
      //   redPackNum
      // })
    }
    
    totalPrice = that.round(totalPrice - redPackNum);
    this.setData({
      totalPrice,
      redPackNum
    })
  },
  // 四舍五入 保留两位小数，不够补零
  round(x){
    var f = parseFloat(x);
    if (f == 0) {
      return 0
    }
    if (isNaN(f)) {
      return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
      rs = s.length;
      s += '.';
    }
    while (s.length <= rs + 2) {
      s += '0';
    }
    return s;    
  },
  // 格式化金额
  moneyFormat(number){

    number = (number + '').replace(/[^0-9+-Ee.]/g, '');

    var n = !isFinite(+number) ? 0 : +number,
    prec = 2,       //小数点位数
    sep = ' ',    //千分位
    dec = '.',   //小数点
    roundtag = "ceil", //舍入参数，默认 "ceil" 向上取
    s = '',

    toFixedFix = function (n, prec) {

      var k = Math.pow(10, prec);
      console.log();

      return '' + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec * 2))).toFixed(prec * 2)) / k;
    };
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    var re = /(-?\d+)(\d{3})/;
    while(re.test(s[0])) {
      s[0] = s[0].replace(re, "$1" + sep + "$2");
    }

    if ((s[1] || '').length < prec) {
      s[1] = s[1] || '';
      s[1] += new Array(prec - s[1].length + 1).join('0');
    }
      return s.join(dec);
  }
}))
